package com.gly091020.ohMyPC;

import net.minecraft.client.Minecraft;

import static com.gly091020.ohMyPC.OhMyPC.CONFIG;
import static com.gly091020.ohMyPC.OhMyPC.LOGGER;

public class PCTimerInit {
    private static long startTime;
    private static boolean running;
    private static long pcTimer = 0;
    private static boolean pcTrigger = false;

    public static void start() {
        if (running) return;
        if (!CONFIG.enable) return;

        running = true;
        startTime = System.currentTimeMillis();

        Thread timerThread = new Thread(() -> {
            while (running) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
                if (Minecraft.getInstance().level != null && ((!Minecraft.getInstance().isPaused() &&
                        PCTimerInit.getElapsedMillis() > OhMyPC.CONFIG.maxTime) || Minecraft.getInstance().getFps() <
                        OhMyPC.CONFIG.fps)) {
                    pcTimer += 50;
                } else {
                    pcTrigger = false;
                    pcTimer = 0;
                }
                if (isOhMyPC()) {
                    SoundLoader.tryPlay();
                }
            }
        });

        timerThread.start();
    }

    public static void reset() {
        startTime = System.currentTimeMillis();
    }

    public static long getElapsedMillis() {
        return running ? System.currentTimeMillis() - startTime : 0;
    }

    public static boolean isOhMyPC(){
        if(!pcTrigger && pcTimer > OhMyPC.CONFIG.notRespondingTime){
            pcTrigger = true;
            LOGGER.info("Oh My PC");
            return true;
        }
        return false;
    }
}
